﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cost.Models;
using Cost.Services;
using NBlock.Components.Excel;
using NBlock.Core;
using NBlock.MVCExtensions;

namespace Cost.Controllers
{
    public class WeekDishOrderController : Controller
    {
        #region 构造函数
        private readonly ICostRepository<ReportedOrder> reportedOrderRepository;
        private readonly ICostRepository<DishOrder> dishOrderRepository;
        private readonly ICostRepository<DishOrderItem> dishOrderItemRepository;
        private readonly ICostRepository<DishOrderItemView> dishOrderItemViewRepository;
        private readonly ICostRepository<Dish> dishRepository;
        private readonly ICostRepository<ProjectSite> projectSiteRepository;
        private readonly IEnumService enumService;
        private readonly IExcelImporter excelImporter;
        private readonly OrderService orderService;
        public WeekDishOrderController(ICostRepository<Dish> dishRepository,
            ICostRepository<DishOrder> dishOrderRepository,
            ICostRepository<ReportedOrder> reportedOrderRepository,
            ICostRepository<DishOrderItem> dishOrderItemRepository,
            ICostRepository<DishOrderItemView> dishOrderItemViewRepository,
            IEnumService enumService,
            IExcelImporter excelImporter,
            OrderService orderService,
            ICostRepository<ProjectSite> projectSiteRepository)
        {
            this.dishOrderRepository = dishOrderRepository;
            this.reportedOrderRepository = reportedOrderRepository;
            this.dishRepository = dishRepository;
            this.dishOrderItemRepository = dishOrderItemRepository;
            this.dishOrderItemViewRepository = dishOrderItemViewRepository;
            this.excelImporter = excelImporter;
            this.enumService = enumService;
            this.orderService = orderService;
            this.projectSiteRepository = projectSiteRepository;
        }
        #endregion

        public ActionResult Index(string Id)
        {
            // 获取上报订单的数据（7天每日订单）
            var order = orderService.GetWeekOrder(Id);
            return View(order);
        }

        [HttpPost]
        public JsonResult AddDish(string Id, List<DishOrderItem> items)
        {
            var order = dishOrderRepository.Find(Id);
            TryUpdateModel(order);

            // 追加已经存在的菜肴明细
            var dishItems = items.Where(item => item.Count > 0).ToList();
            var list = dishOrderItemRepository.FindAll(item => item.OrderId == order.Id).ToList();
            dishItems.AddRange(list);

            // 保存正式订单
            orderService.SaveDishOrder(order, dishItems);

            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteItem(string orderId, string itemId)
        {
            orderService.DeleteDishOrderItem(orderId, itemId);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAllItem(string orderId, string Ids)
        {
            orderService.DeleteDishOrderItem(orderId, Ids);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(string orderId, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = dishOrderItemViewRepository.GetPageable(pager, o => o.OrderId == orderId, where);
            var data = pager.ToGridData(pageData);
            return Json(data);
        }

        [HttpPost]
        public JsonResult Tree(string siteId, DateTime beginDate, DateTime endDate)
        {
            var nodes = new List<nbJsonTreeNode>();
            // 获取指定日期的正式订单
            var orders = dishOrderRepository
                .FindAll(o => o.SiteId == siteId && o.OrderType == "正式订单" && o.OrderDate >= beginDate && o.OrderDate <= endDate)
                .OrderBy(o => o.OrderDate)
                .ToList();
            foreach (var order in orders)
            {
                nodes.Add(new nbJsonTreeNode
                {
                    id = order.Id,
                    text = order.OrderDate.ToString("yyyy-MM-dd（dddd）"),
                    value = order.OrderDate.ToString("yyyy-MM-dd"),
                });
            }

            return Json(nodes);
        }

        #region 更改每日订单的菜肴客数
        public ActionResult EditCount(string itemId, string orderId)
        {
            ViewBag.OrderId = orderId;
            ViewBag.ItemId = itemId;
            return View();
        }

        /// <summary>
        /// 更改客数
        /// </summary>
        /// <param name="itemId">菜肴明细Id，可能是一个或者多个</param>
        /// <param name="orderId"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SaveCount(string itemId, string orderId, int count)
        {
            var result = nbAjaxMessage.Successful;
            var order = dishOrderRepository.Find(orderId);
            if (order != null)
            {
                // 追加已经存在的菜肴明细
                var list = dishOrderItemRepository.FindAll(item => item.OrderId == order.Id).ToList();

                // 可能是一个或者多个菜肴明细项，行中的更改客数或者toolbar中的批量更改客数
                var ids = itemId.Split(',');
                var items = list.Where(item => ids.Contains(item.Id));
                if (items != null && items.Count() > 0)
                {
                    foreach (var item in items)
                    {
                        item.Count = count;
                    }
                    orderService.SaveDishOrder(order, list);
                }
                else
                {
                    result.IsSuccess = false;
                    result.Msg = string.Format("找不到指定Id（{0}）的订单菜肴信息", itemId);
                }
            }
            else
            {
                result.IsSuccess = false;
                result.Msg = string.Format("找不到指定Id（{0}）的订单信息", orderId);
            }

            return Json(result);
        }
        #endregion

        #region 更改每日订单的备注
        public ActionResult EditRemark(string orderId)
        {
            var data = dishOrderRepository.Find(orderId);
            return View(data);
        }

        [HttpPost]
        public JsonResult SaveRemark(string Id, string remark)
        {
            var order = dishOrderRepository.Find(Id);

            if (order.State == "上报")
                throw new Exception("订单已经上报，无效操作！");

            order.Remark = remark;
            dishOrderRepository.Save(order);
            return Json(nbAjaxMessage.Successful);
        }
        #endregion

        #region 上报订单
        public ActionResult ReportOrder(string Id)
        {
            var data = reportedOrderRepository.Find(Id);

            if (!data.ReportDate.HasValue)
            {
                data.ReportDate = DateTime.Now;
            }
            if (string.IsNullOrWhiteSpace(data.ReportUserName))
            {
                data.ReportUserId = nbUserContext.Current.CurrentUser.UserId;
                data.ReportUserName = nbUserContext.Current.CurrentUser.UserName;
            }

            return View(data);
        }

        [HttpPost]
        public JsonResult SaveReportOrder(string Id, string password)
        {
            var data = reportedOrderRepository.Find(Id);

            // 判断上报密码是否正确
            var pwd = projectSiteRepository.FindAll(s => s.Id == data.SiteId).Select(s => s.ReportOrderPassword).FirstOrDefault();
            if (password == pwd)
            {
                // 更改订单的状态和统计订单的数量

                TryUpdateModel(data);
                orderService.ReportWeekOrder(data);
                return Json(nbAjaxMessage.Successful);
            }
            else
            {
                return Json(new nbAjaxMessage { IsSuccess = false, Msg = "上报密码错误，请重新输入的正确密码！" });
            }

        }
        #endregion
    }
}
